package com.service;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

@Service
public class MyAccessDecisionManager implements AccessDecisionManager {

	//判断该用户是否有权限
    @Override 
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

    	Iterator<ConfigAttribute> iter = configAttributes.iterator();
        while( iter.hasNext() ) {
        	ConfigAttribute configAttribute = iter.next();
            for(GrantedAuthority auth : authentication.getAuthorities()) {
            	//对比由参数传入的用户是否有访问网页的权限
                if(   auth.getAuthority().equals(configAttribute.getAttribute()) ) {
                    //匹配到权限，则退出，继续后继流程
                	return;
                }
            }
        }
        //如果都没匹配到
        throw new AccessDeniedException("No enough Authority");
    }

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

    
}